package com.qcxq.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qcxq.dto.Result;
import com.qcxq.dto.UserDTO;
import com.qcxq.entity.Follow;
import com.qcxq.mapper.FollowMapper;
import com.qcxq.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcxq.service.IUserService;
import com.qcxq.utils.RedisConstants;
import com.qcxq.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;
    @Override
    public Result followUser(Long id, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        //redis的key
        String key = RedisConstants.FOLLOWS_KEY + userId;
        //关注
        if (BooleanUtil.isTrue(isFollow)){
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(id);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                stringRedisTemplate.opsForSet().add(key,id.toString());
            }
        }
        //取关
        else{
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", id));
            if (isSuccess){
                stringRedisTemplate.opsForSet().remove(key,id.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollowed(Long id) {
        Long userId = UserHolder.getUser().getId();
        Integer count = this.query().eq("user_id", userId)
                .eq("follow_user_id", id)
                .count();
        return Result.ok(count>0);
    }

    @Override
    public Result commonFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        //当前用户的rediskey
        String selfKey = RedisConstants.FOLLOWS_KEY+userId;
        //对方的rediskey
        String key = RedisConstants.FOLLOWS_KEY+id;
        //查询共同关注
        Set<String> set = stringRedisTemplate.opsForSet().intersect(selfKey, key);
        if (set==null||set.isEmpty())
            return Result.ok(Collections.emptyList());
        List<Long> ids = set.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> list = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(list);
    }
}
